package com.sms.auditservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sms.common.result.Result;
import com.sms.auditservice.entity.SmsAudit;
import com.sms.auditservice.entity.SmsLog;
import com.sms.auditservice.mapper.SmsAuditMapper;
import com.sms.auditservice.mapper.SmsLogMapper;
import com.sms.auditservice.service.SmsAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SmsAuditServiceImpl extends ServiceImpl<SmsLogMapper, SmsLog> implements SmsAuditService {
    
    @Autowired
    private SmsLogMapper smsLogMapper;
    
    @Autowired
    private SmsAuditMapper smsAuditMapper;
    
    @Override
    @Transactional
    public Result<String> recordSmsLog(String taskId, Long userId, Long templateId, String phoneNumber, 
                                      String content, Integer status, String channelCode, String result, String errorMessage) {
        SmsLog smsLog = new SmsLog();
        smsLog.setTaskId(taskId);
        smsLog.setUserId(userId);
        smsLog.setTemplateId(templateId);
        smsLog.setPhoneNumber(phoneNumber);
        smsLog.setContent(content);
        smsLog.setStatus(status);
        smsLog.setChannelCode(channelCode);
        smsLog.setSendTime(LocalDateTime.now());
        smsLog.setResult(result);
        smsLog.setErrorMessage(errorMessage);
        
        smsLogMapper.insert(smsLog);
        
        log.info("记录短信发送日志，任务ID: {}, 手机号: {}, 状态: {}", taskId, phoneNumber, status);
        return Result.success("日志记录成功");
    }
    
    @Override
    @Transactional
    public Result<String> recordAuditLog(Integer auditType, String auditObjectId, String auditObjectType, 
                                        Integer auditOperation, Long operatorId, String operatorName,
                                        String beforeStatus, String afterStatus, String operationDesc) {
        SmsAudit audit = new SmsAudit();
        audit.setAuditType(auditType);
        audit.setAuditObjectId(auditObjectId);
        audit.setAuditObjectType(auditObjectType);
        audit.setAuditOperation(auditOperation);
        audit.setOperatorId(operatorId);
        audit.setOperatorName(operatorName);
        audit.setBeforeStatus(beforeStatus);
        audit.setAfterStatus(afterStatus);
        audit.setOperationDesc(operationDesc);
        audit.setOperationTime(LocalDateTime.now());
        
        smsAuditMapper.insert(audit);
        
        log.info("记录审计日志，审计类型: {}, 操作: {}, 操作人: {}", auditType, auditOperation, operatorName);
        return Result.success("审计日志记录成功");
    }
    
    @Override
    public Result<Object> getSendStatisticsByDate(String startDate, String endDate) {
        // 这里应该使用SQL聚合查询
        // 为了演示，返回模拟数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalCount", 1000);
        statistics.put("successCount", 950);
        statistics.put("failCount", 50);
        statistics.put("successRate", "95%");
        
        return Result.success(statistics);
    }
    
    @Override
    public Result<Object> getSendStatisticsByTemplate(String startDate, String endDate) {
        // 这里应该使用SQL聚合查询
        // 为了演示，返回模拟数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("template1", 300);
        statistics.put("template2", 250);
        statistics.put("template3", 200);
        statistics.put("template4", 150);
        statistics.put("template5", 100);
        
        return Result.success(statistics);
    }
    
    @Override
    public Result<Object> getSendStatisticsByChannel(String startDate, String endDate) {
        // 这里应该使用SQL聚合查询
        // 为了演示，返回模拟数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("aliyun", 400);
        statistics.put("tencent", 350);
        statistics.put("huawei", 250);
        
        return Result.success(statistics);
    }
    
    @Override
    public Result<Object> getSendStatisticsByUser(String startDate, String endDate) {
        // 这里应该使用SQL聚合查询
        // 为了演示，返回模拟数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("user1", 150);
        statistics.put("user2", 120);
        statistics.put("user3", 100);
        statistics.put("user4", 80);
        statistics.put("user5", 60);
        
        return Result.success(statistics);
    }
    
    @Override
    public Result<Object> getSmsLogList(Integer pageNum, Integer pageSize, String phoneNumber, 
                                       Integer status, String startDate, String endDate) {
        Page<SmsLog> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsLog> queryWrapper = new QueryWrapper<>();
        
        if (StrUtil.isNotBlank(phoneNumber)) {
            queryWrapper.like("phone_number", phoneNumber);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        if (StrUtil.isNotBlank(startDate)) {
            queryWrapper.ge("send_time", startDate);
        }
        if (StrUtil.isNotBlank(endDate)) {
            queryWrapper.le("send_time", endDate);
        }
        
        queryWrapper.orderByDesc("send_time");
        
        Page<SmsLog> result = page(page, queryWrapper);
        return Result.success(result);
    }
    
    @Override
    public Result<Object> getAuditLogList(Integer pageNum, Integer pageSize, Integer auditType, 
                                         Integer auditOperation, String startDate, String endDate) {
        Page<SmsAudit> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsAudit> queryWrapper = new QueryWrapper<>();
        
        if (auditType != null) {
            queryWrapper.eq("audit_type", auditType);
        }
        if (auditOperation != null) {
            queryWrapper.eq("audit_operation", auditOperation);
        }
        if (StrUtil.isNotBlank(startDate)) {
            queryWrapper.ge("operation_time", startDate);
        }
        if (StrUtil.isNotBlank(endDate)) {
            queryWrapper.le("operation_time", endDate);
        }
        
        queryWrapper.orderByDesc("operation_time");
        
        Page<SmsAudit> result = page(page, queryWrapper);
        return Result.success(result);
    }
    
    @Override
    public Result<String> exportSmsLog(String startDate, String endDate) {
        // 这里应该实现Excel导出功能
        // 为了演示，返回成功消息
        log.info("导出短信日志，开始日期: {}, 结束日期: {}", startDate, endDate);
        return Result.success("短信日志导出成功");
    }
    
    @Override
    public Result<String> exportAuditLog(String startDate, String endDate) {
        // 这里应该实现Excel导出功能
        // 为了演示，返回成功消息
        log.info("导出审计日志，开始日期: {}, 结束日期: {}", startDate, endDate);
        return Result.success("审计日志导出成功");
    }
} 